package controllers;

import data.users.UserDataGateway;
import models.general.UserDTO;
import models.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import play.data.validation.Validation;
import play.mvc.Controller;
import play.mvc.Scope;

/**
 * @author Karl J. Karlsson
 * @version 0.9, 6. Oct 2011
 */
public class UserController extends Controller
{
    public static void login()
    {
        render();
    }

    public static void loginUser(String username, String password)
    {
        ApplicationContext ctx = new FileSystemXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) ctx.getBean("userService");
        UserDataGateway userDataGateway = (UserDataGateway) ctx.getBean("userDataGateway");

        userService.setUserDataGateway(userDataGateway);

        Validation.required("username", username);
        Validation.required("password", password);

        if (Validation.hasErrors())
        {
            params.flash();
            Validation.keep();
            login();
        }
        UserDTO user = null;
        user = userService.login(username, password);

        if (user == null)
        {
            Validation.addError("error", "Username or password is incorrect.");
            params.flash();
            Validation.keep();
            login();
        }
        Scope.Session.current().put("user", user);
        Application.index(); //TODO?!?! - PostController.Dashboard() t.d.


    }

}
